package com.yyw.gulimall.authserver.service.impl;

import cn.gjing.http.HttpClient;
import cn.gjing.http.HttpMethod;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yyw.common.enums.common.OAuth2SourceEnum;
import com.yyw.common.exception.OAuth2LoginException;
import com.yyw.common.exception.UserLoginException;
import com.yyw.common.utils.R;
import com.yyw.gulimall.authserver.abstracts.RootOAuth2Service;
import com.yyw.gulimall.authserver.feign.MemberFeign;
import com.yyw.common.to.oauth.MemberVo;
import com.yyw.gulimall.authserver.vo.weibo.AccessTokenResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname WeiboOAuth2ServiceImpl
 * @Description 微博认证服务
 * @Date 2020/12/16 11:06
 * @Created yyw
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WeiboOAuth2ServiceImpl extends RootOAuth2Service {

    private final MemberFeign memberFeign;

    /**
     * 读取配置文件，获取微博配置参数
     */
    @Value("${oauth2.weibo.clientId}")
    public String clientId;
    @Value("${oauth2.weibo.clientSecret}")
    public String clientSecret;
    @Value("${oauth2.weibo.grantType}")
    public String grantType;
    @Value("${oauth2.weibo.redirectUri}")
    public String redirectUri;

    @Override
    public MemberVo login(String code) throws OAuth2LoginException {
        if (!StringUtils.isEmpty(code)) {
            // 1. 发送请求，换取AccessToken
            // https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
            // &grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
            Map<String, String> map = new HashMap<>();
            map.put("client_id", clientId);
            map.put("client_secret", clientSecret);
            map.put("grant_type", grantType);
            map.put("redirect_uri", redirectUri);
            map.put("code", code);
            try {
                String result = HttpClient.builder("https://api.weibo.com/oauth2/access_token", HttpMethod.POST, String.class)
                        .param(map)
                        .fallback(e -> {
                            // 发生错误
                            log.error(e);
                            throw new UserLoginException(e);
                        })
                        .execute().get();
                log.info("换取成功: {}", result);
                AccessTokenResult accessToken = JSON.parseObject(result, AccessTokenResult.class);

                // TODO: 2020/12/16 调用远程服务超时待解决
                // 2. 将数据发送给会员服务。判断是登录还是注册，再跳回主页
                R r = memberFeign.oauthLogin(accessToken, OAuth2SourceEnum.OAUTH2_WEIBO.getName());
                if (!Objects.equals(0, r.get("code"))) {
                    // 发送了异常
                    throw new OAuth2LoginException("微博登录发生错误，请稍后再试：" + r.get("msg"));
                }
                MemberVo data = r.getData("data", new TypeReference<MemberVo>() {
                });  //2.00IscixGw_IQoC95bf5ac8b   157679999
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                throw new OAuth2LoginException("微博登录发生错误，请稍后再试" + e.getMessage());
            }
        }
        throw new OAuth2LoginException("微博登录发生错误，认证码[code]不存在");
    }
}
